package com.buobao.reflect.demo;

import com.buobao.reflect.demo.entity.Employee;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 反射方法调用示例
 */
public class MethodSample {
    public static void main(String[] args){
        try {
            Class employeeClass = Class.forName("com.buobao.reflect.demo.entity.Employee");
            Constructor constructor = employeeClass.getConstructor(new Class[]{int.class,String.class,float.class,String.class, Date.class});
            Employee employee = (Employee) constructor.newInstance(new Object[]{1002,"lisi",3500,"designer",new Date()});
            System.out.println(employee);
            //调用公有方法
            Method updateMethod = employeeClass.getMethod("updateSalary",new Class[]{Float.class});
            Employee employee1 = (Employee) updateMethod.invoke(employee,new Object[]{-200f});
            System.out.println(employee1);
            //调用私有方法
            Method changeMethod = employeeClass.getDeclaredMethod("chageName",new Class[]{String.class});
            changeMethod.setAccessible(true);
            Employee employee2 = (Employee) changeMethod.invoke(employee,new Object[]{"newName"});
            System.out.println(employee2);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
